<template>
  <div class="data-table">
    <!-- 表格工具栏 -->
    <div v-if="showToolbar" class="table-toolbar">
      <div class="toolbar-left">
        <slot name="toolbar-left">
          <el-button
            v-if="showAdd"
            type="primary"
            @click="$emit('add')"
          >
            <el-icon><Plus /></el-icon>
            新增
          </el-button>
          <el-button
            v-if="showBatchDelete && selectedRows.length > 0"
            type="danger"
            @click="$emit('batchDelete', selectedRows)"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </slot>
      </div>
      
      <div class="toolbar-right">
        <slot name="toolbar-right">
          <!-- 刷新 -->
          <el-tooltip content="刷新" placement="top">
            <el-button
              circle
              @click="$emit('refresh')"
            >
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-tooltip>
          
          <!-- 列设置 -->
          <el-tooltip content="列设置" placement="top">
            <el-button
              circle
              @click="showColumnSetting = true"
            >
              <el-icon><Setting /></el-icon>
            </el-button>
          </el-tooltip>
        </slot>
      </div>
    </div>
    
    <!-- 表格 -->
    <el-table
      ref="tableRef"
      :data="data"
      :loading="loading"
      :height="tableHeight"
      :stripe="stripe"
      :border="border"
      :size="size"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      v-bind="$attrs"
    >
      <!-- 选择列 -->
      <el-table-column
        v-if="showSelection"
        type="selection"
        width="55"
        align="center"
      />
      
      <!-- 序号列 -->
      <el-table-column
        v-if="showIndex"
        type="index"
        label="序号"
        width="60"
        align="center"
      />
      
      <!-- 数据列 -->
      <template v-for="column in visibleColumns" :key="column.prop">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :align="column.align || 'left'"
          :sortable="column.sortable"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <template #default="scope">
            <slot
              :name="column.prop"
              :row="scope.row"
              :column="column"
              :$index="scope.$index"
            >
              {{ scope.row[column.prop] }}
            </slot>
          </template>
        </el-table-column>
      </template>
      
      <!-- 操作列 -->
      <el-table-column
        v-if="showActions"
        label="操作"
        :width="actionWidth"
        :fixed="actionFixed"
        align="center"
      >
        <template #default="scope">
          <slot
            name="actions"
            :row="scope.row"
            :$index="scope.$index"
          >
            <el-button
              type="primary"
              link
              size="small"
              @click="$emit('edit', scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="$emit('delete', scope.row)"
            >
              删除
            </el-button>
          </slot>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div v-if="showPagination" class="table-pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="pageSizes"
        :layout="paginationLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 列设置弹窗 -->
    <el-dialog
      v-model="showColumnSetting"
      title="列设置"
      width="400px"
    >
      <div class="column-setting">
        <el-checkbox
          v-model="checkAll"
          :indeterminate="isIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-divider />
        <el-checkbox-group v-model="checkedColumns" @change="handleCheckedColumnsChange">
          <div v-for="column in columns" :key="column.prop" class="column-item">
            <el-checkbox :label="column.prop">{{ column.label }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Plus, Delete, Refresh, Setting } from '@element-plus/icons-vue'

export interface TableColumn {
  prop: string
  label: string
  width?: string | number
  minWidth?: string | number
  fixed?: boolean | string
  align?: 'left' | 'center' | 'right'
  sortable?: boolean | string
  showOverflowTooltip?: boolean
}

interface Props {
  data: any[]
  columns: TableColumn[]
  loading?: boolean
  showToolbar?: boolean
  showAdd?: boolean
  showBatchDelete?: boolean
  showSelection?: boolean
  showIndex?: boolean
  showActions?: boolean
  showPagination?: boolean
  total?: number
  currentPage?: number
  pageSize?: number
  pageSizes?: number[]
  paginationLayout?: string
  tableHeight?: string | number
  stripe?: boolean
  border?: boolean
  size?: 'large' | 'default' | 'small'
  actionWidth?: string | number
  actionFixed?: boolean | string
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  columns: () => [],
  loading: false,
  showToolbar: true,
  showAdd: true,
  showBatchDelete: true,
  showSelection: false,
  showIndex: false,
  showActions: true,
  showPagination: true,
  total: 0,
  currentPage: 1,
  pageSize: 20,
  pageSizes: () => [10, 20, 50, 100],
  paginationLayout: 'total, sizes, prev, pager, next, jumper',
  stripe: true,
  border: true,
  size: 'default',
  actionWidth: 150,
  actionFixed: 'right'
})

const emit = defineEmits<{
  add: []
  edit: [row: any]
  delete: [row: any]
  batchDelete: [rows: any[]]
  refresh: []
  'update:currentPage': [page: number]
  'update:pageSize': [size: number]
  'size-change': [size: number]
  'current-change': [page: number]
  'selection-change': [selection: any[]]
  'sort-change': [sort: { column: any; prop: string; order: string | null }]
}>()

const tableRef = ref()
const selectedRows = ref<any[]>([])
const showColumnSetting = ref(false)
const checkedColumns = ref<string[]>([])
const checkAll = ref(true)
const isIndeterminate = ref(false)

// 可见列
const visibleColumns = computed(() => {
  return props.columns.filter(column => checkedColumns.value.includes(column.prop))
})

// 初始化选中的列
watch(() => props.columns, (newColumns) => {
  checkedColumns.value = newColumns.map(column => column.prop)
}, { immediate: true })

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 处理排序变化
const handleSortChange = (sort: { column: any; prop: string; order: string | null }) => {
  emit('sort-change', sort)
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  emit('update:currentPage', page)
  emit('current-change', page)
}

// 处理页大小变化
const handleSizeChange = (size: number) => {
  emit('update:pageSize', size)
  emit('size-change', size)
}

// 处理全选变化
const handleCheckAllChange = (val: boolean) => {
  checkedColumns.value = val ? props.columns.map(column => column.prop) : []
  isIndeterminate.value = false
}

// 处理列选择变化
const handleCheckedColumnsChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === props.columns.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.columns.length
}
</script>

<style scoped>
.data-table {
  background: #fff;
  border-radius: 4px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.toolbar-left {
  display: flex;
  gap: 8px;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.table-pagination {
  display: flex;
  justify-content: flex-end;
  padding: 16px;
  border-top: 1px solid #e8e8e8;
}

.column-setting {
  max-height: 400px;
  overflow-y: auto;
}

.column-item {
  padding: 4px 0;
}
</style>